﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Microsoft.Xna.Framework;

using FerrScript;

namespace XNAFerrScriptTester
{
    class ScriptObjectComponent : DrawableGameComponent
    {
        FScript script;

        public ScriptObjectComponent(Game aGame, string aScriptFileName)
            :base(aGame)
        {
            // load and compile the script
            StreamReader reader = new StreamReader(aScriptFileName);
            script = FerrScriptCompiler.Inst.Compile(reader.ReadToEnd());
            reader.Close();

            // throw an exception if it's a bad script
            if (FerrScriptCompiler.Inst.Errors.Count > 0)
            {
                string throwString = "";
                for (int i = 0; i < FerrScriptCompiler.Inst.Errors.Count; i++)
                    throwString += FerrScriptCompiler.Inst.Errors[i] + "\n";

                throw new Exception(throwString);
            }
        }

        protected override void LoadContent()
        {
            script.CallFunction("OnLoad");
            base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            script.CallFunction("OnUpdate");
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            script.CallFunction("OnDraw");
            base.Draw(gameTime);
        }
    }
}
